package com.myblog.job;

import com.myblog.Utils.RedisCache;
import com.myblog.domain.contants.GlobalConstants;
import com.myblog.domain.entity.Article;
import com.myblog.mapper.ArticleMapper;
import com.myblog.services.ArticleService;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class updateViewCountJob {

    @Resource
    ArticleService articleService;
    @Resource
    RedisCache redisCache;
    @Scheduled(cron = "* 0/15 * * * ? ")
    public void updateViewCount(){
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(GlobalConstants.VIEWCOUNT_MAP_NAME);
        Set<String> keys=viewCountMap.keySet();
        List<Article> article=new ArrayList<>();
        for (String key: keys) {
            Article newArticle=new Article(Long.parseLong(key),viewCountMap.get(key));
            article.add(newArticle);
        }

//        Set<Map.Entry<String, Integer>> entries = viewCountMap.entrySet();
//        List<Article> article = entries.stream()
//                .map(stringIntegerEntry -> new Article(Long.valueOf(stringIntegerEntry.getKey()), stringIntegerEntry.getValue().longValue()))
//                .collect(Collectors.toList());

        articleService.updateBatchById(article);
    }
}
